package org.dreamwork.jasmine2.parser;

import org.dreamwork.text.TextParser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-2-3
 * Time: 15:45:25
 */
public class Test {
    public static void main (String[] args) throws Exception {
        Pattern p = Pattern.compile ("(<%[#=](.*)%>)", Pattern.MULTILINE);
        String s  = "Other.jsp?id=<%# DataBinder.eval(obj, \"id\")%>&title=<%= DataBinder.eval (obj, \"title\")%>";
//        String s = "----<>abc<>----<>def<>----<>ghi<>----<>jkl<>----<>mno<>----";
        Matcher m = p.matcher (s);
        StringBuffer buffer = new StringBuffer ();
        while (m.find ()) {
/*
            for (int i = 0; i <= m.groupCount (); i ++)
            System.out.println (m.group (i));
*/
            buffer.append ('"');
            m.appendReplacement (buffer, "\" + ");
//            System.out.println (m.group (1));
            buffer.append (m.group (2)).append (" + ");
        }
        buffer.append ('"');
        m.appendTail (buffer);
        buffer.append ('"');

        System.out.println (buffer);

        new TestParser (s).parse ();
    }

    private static class TestParser extends TextParser {
        public TestParser (String content) {
            super (content);
        }

        public void parse () {
            StringBuffer sb = new StringBuffer ();
            String limit = "<%";
            int lastPos = cursor;
            while (cursor < stream.length - 1) {
                Segment s = this.skipUntil (limit);
                if (s != null) {
                    lastPos = cursor;
                    String expr = s.toString ().trim ();
                    if (expr.length () > 0) {
                        if (sb.length () > 0) sb.append ("+");
                        if(limit.equals ("<%")) {
                            sb.append ('"').append (s).append ('"');
                        } else {
                            if (expr.charAt (0) == '#' || expr.charAt (0) == '=')
                                expr = expr.substring (1);
                            sb.append (expr);
                        }
                    }
                } else {
                    sb.append ('"').append (new String (stream, lastPos, stream.length - lastPos)).append ('"');
                }
                if ("<%".equals (limit)) limit = "%>";
                else limit = "<%";
            }
            String statement = sb.toString ().replaceAll ("\\\\", "\\\\");
            statement = statement.replaceAll ("\\\"", "\\\\\"");
            statement = '"' + statement + '"';
        }
    }
}
